package server

import (
	"context"
	"fmt"
	"io"
	"time"

	"gitee.com/wang1974/go-grpcservice/data"
	"gitee.com/wang1974/go-grpcservice/pb"
	"google.golang.org/grpc/metadata"
)

type EmployeeService struct {
	pb.UnimplementedEmployeeServiceServer
}

func (msg *EmployeeService) GetByNo(ctx context.Context, req *pb.GetByNoRequset) (*pb.EmployeeResponse, error) {
	for _, e := range data.Employees {
		if req.No == e.No {
			return &pb.EmployeeResponse{
				Employee: &e,
			}, nil
		}
	}
	return &pb.EmployeeResponse{}, nil
}

func (msg *EmployeeService) GetAll(req *pb.GetAllRequest, steam pb.EmployeeService_GetAllServer) error {
	for _, e := range data.Employees {

		steam.Send(&pb.EmployeeResponse{
			Employee: &e,
		})
		time.Sleep(2 * time.Second)

	}
	return nil
}
func (msg *EmployeeService) AddPhoto(stream pb.EmployeeService_AddPhotoServer) error {
	md, ok := metadata.FromIncomingContext(stream.Context())
	if ok {
		fmt.Println("employee", md["no"][0])
	}
	img := []byte{}
	for {
		data, err := stream.Recv()
		if err == io.EOF {
			fmt.Printf("file size:%d\n", len(img))
			return stream.SendAndClose(&pb.AddPhotoResponse{IsOk: true})
		}
		if err != nil {
			return err
		}
		fmt.Printf("file received: %d", len(data.Data))
		img = append(img, data.Data...)
	}
}
func (msg *EmployeeService) Save(context.Context, *pb.EmployeeRequest) (*pb.EmployeeResponse, error) {
	return nil, nil
}
func (msg *EmployeeService) SaveAll(stream pb.EmployeeService_SaveAllServer) error {
	for {
		emp, err := stream.Recv()
		if err == io.EOF {
			break
		}
		if err != nil {
			return err
		}
		data.Employees = append(data.Employees, *emp.Employee)
		stream.Send(&pb.EmployeeResponse{Employee: emp.Employee})
	}
	for _, emp := range data.Employees {
		fmt.Println(emp)
	}
	return nil
}
